package com.onepiece.shipelves.common.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xiongrt
 */
public class StringUtil {

    private static Pattern INTERGE_PATTERN = Pattern.compile("(\\d+)");
    private static Pattern DECIMALS_PATTERN = Pattern.compile("(\\d+\\.\\d+)");

    /**
     * 过滤特殊字符
     *
     * @param keyword
     * @return
     */
    public static String escapeExprSpecialWord(String keyword) {
        String[] fbsArr = {"-", ",", "%", " "};
        for (String key : fbsArr) {
            if (keyword.contains(key)) {
                keyword = keyword.replace(key, "");
            }
        }
        return keyword;
    }

    /**
     * 保留小数点后四位
     *
     * @param ope
     * @return
     */
    public static String getDecimalPoint(Object ope) {
        DecimalFormat decimalFormat = new DecimalFormat("0.0000");
        return decimalFormat.format(ope);
    }

    public static String cutByMaxByteLength(String old, int maxByteLength) {
        byte[] utf8 = old.getBytes();
        if (utf8.length < maxByteLength) {
            maxByteLength = utf8.length;
        }
        int n16 = 0;
        int advance = 1;
        int i = 0;
        while (i < maxByteLength) {
            advance = 1;
            if ((utf8[i] & 0x80) == 0) {
                i += 1;
            } else if ((utf8[i] & 0xE0) == 0xC0) {
                i += 2;
            } else if ((utf8[i] & 0xF0) == 0xE0) {
                i += 3;
            } else {
                i += 4;
                advance = 2;
            }
            if (i <= maxByteLength) {
                n16 += advance;
            }
        }
        return old.substring(0, n16);
    }


    /**
     * 蛇形转驼峰
     *
     * @param orderField
     * @return string
     */
    public static String toHumpStr(String orderField) {
        String[] strs = orderField.split("_");
        StringBuilder builder = new StringBuilder();
        for (String str : strs) {
            if (builder.length() == 0) {
                builder.append(str);
            } else {
                builder.append(str.substring(0, 1).toUpperCase());
                builder.append(str.substring(1));
            }
        }
        return builder.toString();
    }

    public static boolean isNumber(String str) {
        return str.matches("-?[0-9]+.*[0-9]*");
    }

    public static boolean isMobileNumber(String mobiles) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(mobiles);
        b = m.matches();
        return b;
    }

    /**
     * 获取某字符串在另个字符串出现次数
     *
     * @param str
     * @param s
     * @return int
     */
    public static int countString(String str, String s) {
        String str1 = str.replaceAll(s, "");
        int len1 = str.length(), len2 = str1.length(), len3 = s.length();
        int count = (len1 - len2) / len3;
        return count;
    }

    /**
     * 从字符串中提取字符数字列表
     *
     * @param str
     * @return List<Double>
     */
    public static List<Double> extractionNumFromStr(String str) {
        //先判断有没有整数，如果没有整数那就肯定就没有小数
        Matcher m = INTERGE_PATTERN.matcher(str);
        String result = "";
        List<Double> numbers = new ArrayList<>(5);
        if (m.find()) {
            m = DECIMALS_PATTERN.matcher(str);
            //遍历小数部分
            while (m.find()) {
                result = m.group(1) == null ? "" : m.group(1);
                int i = str.indexOf(result);
                String s = str.substring(i, i + result.length());
                numbers.add(Double.valueOf(s));
                //排除小数的整数部分和另一个整数相同的情况下，寻找整数位置出现错误的可能，还有就是寻找重复的小数
                // 例子中是排除第二个345.56时第一个345.56产生干扰和寻找整数345的位置时，前面的小数345.56会干扰
                str = str.substring(0, i) + str.substring(i + result.length());
            }
            //遍历整数
            m = INTERGE_PATTERN.matcher(str);
            while (m.find()) {
                result = m.group(1) == null ? "" : m.group(1);
                int i = str.indexOf(result);
                String s = str.substring(i, i + result.length());
                numbers.add(Double.valueOf(s));
                str = str.substring(0, i) + str.substring(i + result.length());
            }
        }
        return numbers;
    }


    /**
     * 验证邮箱地址是否正确
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean equalStr(String str1, String str2) {
        if (!StringUtils.isEmpty(str1) && !StringUtils.isEmpty(str2)) {
            return str1.equals(str2);
        }
        return false;
    }

    /**
     * 验证字符串内容是否包含下列非法字符<br>
     * `~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆
     *
     * @param content 字符串内容
     * @return 't'代表不包含非法字符，otherwise代表包含非法字符。
     */
    public static boolean validateLegalString(String content) {
        String illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆";
        for (int i = 0; i < content.length(); i++) {
            for (int j = 0; j < illegal.length(); j++) {
                if (content.charAt(i) == illegal.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 生成6位随机数
     */
    public static String randomCode() {
        return RandomStringUtils.random(6, "1234567890");
    }

}
